/*
 * The contents of this web application are subject to the Mozilla Public License Version 
 * 1.1 (the "License"); you may not use this web application except in compliance with 
 * the License. You may obtain a copy of the License at http://www.mozilla.org/MPL/.
 * 
 * Software distributed under the License is distributed on an "AS IS" basis, 
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License 
 * for the specific language governing rights and limitations under the License.
 * 
 * The Original Code is owned by and the Initial Developer of the Original Code is 
 * Composite A/S (Danish business reg.no. 21744409). All Rights Reserved
 * 
 * Section 11 of the License is EXPRESSLY amended to include a provision stating 
 * that any dispute, including but not limited to disputes related to the enforcement 
 * of the License, to which Composite A/S as owner of the Original Code, as Initial 
 * Developer or in any other role, becomes a part to shall be governed by Danish law 
 * and be initiated before the Copenhagen City Court ("K�benhavns Byret")            
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Workflow.Activities;
using Composite.C1Console.Actions;
using Composite.Data;
using Composite.Data.Types;
using Composite.Core.Extensions;
using Composite.Core.ResourceSystem;
using Composite.Data.Validation.ClientValidationRules;
using Composite.C1Console.Workflow;


namespace Composite.Plugins.Elements.ElementProviders.MediaFileProviderElementProvider
{
    [EntityTokenLock()]
    [AllowPersistingWorkflow(WorkflowPersistingType.Idle)]
    public sealed partial class EditMediaFolderWorkflow : Composite.C1Console.Workflow.Activities.FormsWorkflow
    {
        public EditMediaFolderWorkflow()
        {
            InitializeComponent();
        }



        private void initializeCodeActivity_ExecuteCode(object sender, EventArgs e)
        {
            IMediaFileFolder folder = this.GetDataItemFromEntityToken<IMediaFileFolder>();
            IMediaFileStore store = DataFacade.GetData<IMediaFileStore>(x => x.Id == folder.StoreId).First();
            
            this.Bindings.Add("FolderTitle", folder.Title);
            this.Bindings.Add("FolderDescription", folder.Description);
            this.Bindings.Add("FolderName", folder.Path.GetFolderName('/'));
            this.Bindings.Add("ProvidesMetaData", store.ProvidesMetadata);
            this.Bindings.Add("OldFolderPath", folder.Path);

            this.BindingsValidationRules.Add("FolderName", new List<ClientValidationRule> { new NotNullClientValidationRule() });
            this.BindingsValidationRules.Add("FolderTitle", new List<ClientValidationRule> { new StringLengthClientValidationRule(0, 256) });            
        }


        private string CreateFolderPath()
        {
            string updatedFoldername = this.GetBinding<string>("FolderName");
            string folderPath = this.GetBinding<string>("OldFolderPath");

            string currentName = folderPath.GetFolderName('/');

            folderPath = folderPath.Remove(folderPath.Length - currentName.Length);
            folderPath = folderPath + updatedFoldername;

            return folderPath;
        }


        private void saveCodeActivity_ExecuteCode(object sender, EventArgs e)
        {
            UpdateTreeRefresher updateTreeRefresher = this.CreateUpdateTreeRefresher(this.EntityToken);
            
            IMediaFileFolder folder = this.GetDataItemFromEntityToken<IMediaFileFolder>();            

            folder.Path = CreateFolderPath();
            folder.Title = this.GetBinding<string>("FolderTitle");
            folder.Description = this.GetBinding<string>("FolderDescription");

            DataFacade.Update(folder);

            SetSaveStatus(true);

            updateTreeRefresher.PostRefreshMesseges(folder.GetDataEntityToken());
        }



        private void ValidateInputs(object sender, ConditionalEventArgs e)
        {
            IMediaFileFolder folder = this.GetDataItemFromEntityToken<IMediaFileFolder>();            

            string oldFolderPath = this.GetBinding<string>("OldFolderPath");
            string folderPath = CreateFolderPath();

            if (oldFolderPath != folderPath)
            {
                Guid folderId = folder.Id;

                if (DataFacade.GetData<IMediaFileFolder>()
                    .Any(f => string.Compare(f.Path, folderPath, StringComparison.OrdinalIgnoreCase) == 0
                              && f.Id != folderId))
                {
                    ShowFieldMessage("FolderName", StringResourceSystemFacade.GetString("Composite.Management", "Website.Forms.Administrative.AddNewMediaFolder.FolderNameAlreadyUsed"));
                    e.Result = false;
                    return;
                }

                IEnumerable<string> filenames = DataFacade.GetData<IMediaFile>().Where(f => f.FolderPath == oldFolderPath).Select(f => f.FileName);
                foreach (string filename in filenames)
                {
                    string compositePath = IMediaFileExtensions.GetCompositePath(folder.StoreId, folderPath, filename);
                    if (compositePath.Length > 2048)
                    {
                        this.ShowFieldMessage("FolderName", "${Composite.Management, Website.Forms.Administrative.EditMediaFolder.TotalFilenameToLong.Message}");
                        e.Result = false;
                        return;
                    }
                }
            }            

            e.Result = true;
        }
    }
}
